# -*- coding: utf-8 -*-
"""
Created on Tue Apr 30 16:44:48 2024

@author: YANCL
"""

# P16 中值滤波
# %% 导入库
import cv2
import numpy as np

# %% 生成椒盐噪声的函数
"""
    添加椒盐噪声
    :param image: 输入图像
    :param prob: 噪声比
    :return: 带有椒盐噪声的图像
"""
def salt_pepper_noise(image, prob):
    salt = np.zeros(image.shape, np.uint8)
    thres = 1 - prob
    for i in range(image.shape[0]):
        for j in range(image.shape[1]):
            rdn = np.random.rand()
            if rdn < prob:
                salt[i][j] = 0
            elif rdn > thres:
                salt[i][j] = 255
            else:
                salt[i][j] = image[i][j]
    return salt
# %% 处理
Original = cv2.imread("photo/LenaRGB.bmp", cv2.IMREAD_UNCHANGED)
# Original = cv2.imread("photo/dog.png", cv2.IMREAD_UNCHANGED)
Noise_Salt_Pepper = salt_pepper_noise(Original, 0.025)    # 添加椒盐噪声

# 三种滤波算法
Junzhi   = cv2.blur(Noise_Salt_Pepper,(3,3))    #核 - 权重相等 - 均值滤波
Gassian_Result = cv2.GaussianBlur(Noise_Salt_Pepper, (3,3), 0)
Zhongzhi = cv2.medianBlur(Noise_Salt_Pepper, 3)

# 显示对比
cv2.imshow("original", Original)                    #原始图像
cv2.imshow("Noise_Salt_Pepper", Noise_Salt_Pepper)  #椒盐噪声图像
cv2.imshow("JunZhi_Result",  Junzhi)                #均值滤波图像
cv2.imshow("Gassian_Result", Gassian_Result)
cv2.imshow("Median_Result", Zhongzhi)               #中值滤波图像

cv2.waitKey()
cv2.destroyAllWindows()
